package gwtool.gui.components;

import gwtool.gui.MainController;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.ComboBoxModel;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;

public class JComboCheckBox<T> extends JComboBox<T> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public JComboCheckBox() {

		addStuff();
	}

	public JComboCheckBox(T[] items) {

		super(items);
		addStuff();
	}

	public JComboCheckBox(Vector<T> items) {

		super(items);
		addStuff();
	}

	public JComboCheckBox(ComboBoxModel<T> aModel) {

		super(aModel);
		addStuff();
	}

	@Override
	public void setModel(ComboBoxModel<T> aModel) {

		super.setModel(aModel);
		// addStuff();
	}

	private void addStuff() {

		setRenderer(new ComboBoxRenderer());
		addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent ae) {

				itemSelected();
				MainController.getInstance().updateGui();
			}
		});
	}

	private void itemSelected() {

		if (getSelectedItem() instanceof JCheckBox) {
			JCheckBox jcb = (JCheckBox) getSelectedItem();
			jcb.setSelected(!jcb.isSelected());
		}
	}

	class ComboBoxRenderer implements ListCellRenderer<T> {

		private JLabel defaultLabel;

		public ComboBoxRenderer() {

			setOpaque(true);
		}

		@Override
		public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
				boolean cellHasFocus) {

			if (value instanceof Component) {
				Component c = (Component) value;
				if (isSelected) {
					c.setBackground(list.getSelectionBackground());
					c.setForeground(list.getSelectionForeground());
				} else {
					c.setBackground(list.getBackground());
					c.setForeground(list.getForeground());
				}
				return c;
			} else {
				if (defaultLabel == null) {
					if (value != null) {
						defaultLabel = new JLabel(value.toString());
					} else {
						defaultLabel = new JLabel("");
					}
				} else {
					if (value != null) {
						defaultLabel.setText(value.toString());
					} else {
						defaultLabel.setText("");
					}
				}
				return defaultLabel;
			}
		}
	}
}